<template>
  <div style="width: 100%;">
<!--    <Distpicker v-show="false"  @selected="onSelected" :province="district.province" :city="district.city"
                :area="district.area"></Distpicker>-->
    <el-card class="box-card">
      <div>
        <div style="display: flex;align-items: center;justify-content: space-between">
          <div class="details_Header">
            <div class="deleted_Line"></div>
            <span class="details_HeaderTitle">旅游卡信息</span>
          </div>
          <div style="display: flex">
            <el-button type="primary" v-permission="['touristCard.use']" v-show="form.status === 1" @click="useClick">使用</el-button>
            <el-button type="primary"
                       :loading="auditClicked"
                       v-show="form.status === 2" v-permission="['touristCard.audit']"
                       @click="auditClick">核销
            </el-button>
            <el-button type="primary" v-show="form.status==1" v-permission="['touristCard.transfer']" :loading="transferClicked" @click="transferClick">转赠
            </el-button>
            <el-button type="primary" v-show="form.status==1" v-permission="['touristCard.exchange']" :loading="exchangeSaveClicked" @click="exchangeSaveClick">购物券兑换
            </el-button>
            <el-button type="primary" v-show="form.status==9" v-permission="['touristCard.activity']" :loading="activityClicked" @click="activityClick">激活
            </el-button>
          </div>
        </div>
        <div class="deleted_OrderHeader" style="border-left: none;">
          <el-row :gutter="24">
            <el-col :span="8">
              <span class="deleted_Row_Headings">旅游卡号：</span>
              <span class="deleted_OrderTitle">{{form.sn}}</span>
            </el-col>
            <el-col :span="8">
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">状态：</span>
              <span class="deleted_OrderTitle" style="color: rgb(64, 158, 255)">{{form.status | watchStatus}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">名称：</span>
              <span class="deleted_OrderTitle">{{form.productName}}</span>
            </el-col>
          </el-row>
        </div>
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 30px 0 10px 0;">详细信息</span>
        </div>
        <div>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings">购买人员：</span>
              <span class="deleted_OrderTitle">{{form.memberName}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">受赠人员：</span>
              <span class="deleted_OrderTitle">{{form.receiverName}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">价格：</span>
              <span class="deleted_OrderTitle">{{form.price}}</span>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings">订单日期：</span>
              <span class="deleted_OrderTitle">{{form.orderDate | dateFormatter}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">订单编号：</span>
              <span class="deleted_OrderTitle">{{form.orderSn}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">有效期：</span>
              <span class="deleted_OrderTitle">{{form.validStartDate | dateFormatter}} 至 {{form.validEndDate | dateFormatter}}</span>
            </el-col>
          </el-row>
        </div>

        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 30px 0 10px 0;">用户信息</span>
        </div>
        <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings">身份证：</span>
              <span class="deleted_OrderTitle">{{form.identityId}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">用户名称：</span>
              <span class="deleted_OrderTitle">{{form.name}}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">手机号：</span>
              <span class="deleted_OrderTitle">{{form.phone}}</span>
            </el-col>
          </el-row>

      </div>
    </el-card>


    <el-dialog
      title="转赠"
      :visible.sync="transferVisible"
      width="40%"
      v-el-drag-dialog
      append-to-body
      :before-close="transferClose">
      <div style="position: relative;">
        <el-form ref="transferForm" :model="form" :rules="rules" label-width="90px">
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="旅游卡号:">
                <span>{{ form.sn}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="购买人:">
                <span>{{memberName}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24"  class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="受赠人:" :prop="'receiver'" :rules="rules.receiverName">
                <el-select v-model="form.receiverName" value-key="id" clearable placeholder="请选择客户"
                      filterable @focus="getMemberList" @change="selectMember" :filter-method="queryMember">
                  <el-option v-for="item in memberIdOptions" style="width: 400px;" :key="item.id" :label="item.name" :value="item">
                      <div style="display: flex">
                        <span style="width: 70px;">{{ item.code }}</span>
                        <span style="float: left;width: 150px;overflow: hidden;text-overflow: ellipsis;">{{item.name}}</span>
                        <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{item.mobile}}</span>
                    <!--     <div style="width: 100px;">
                          <span style="color: #8492a6; font-size: 8px;">{{ item.address }}</span>
                        </div> -->
                      </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toSearchMember">搜索客户</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div style="
            display: flex;
            justify-content:space-between;
            align-items: center;
            margin-top: 30px;margin-left: 50px;
          ">
          <el-button type="primary" :loading="transferSaveClick" @click="transferSave">转赠</el-button>
        </div>

      </div>
    </el-dialog>
    <el-dialog
      title="双击选择客户"
      :visible.sync="memberTableVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="memberTableClose">
      <div style="position: relative;">
        <member-table :key="times" @memberDouble="memberDouble" @memberTableClose="memberTableClose"></member-table>
      </div>
    </el-dialog>
    <el-dialog
      title="使用旅游卡"
      :visible.sync="useVisible"
      width="40%"
      v-el-drag-dialog
      append-to-body
      :before-close="useClose">
      <div style="position: relative;">
        <el-form ref="useForm"  :model="form" :rules="rules" label-width="90px">
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="旅游卡号:">
                <span>{{form.sn}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="购买人:">
                <span>{{memberName}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="身份证:" :prop="'identityId'" :rules="rules.identityId">
                 <el-input v-model="form.identityId" type="text" placeholder="请输入身份证"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="姓  名:" :prop="'name'" :rules="rules.name">
                 <el-input v-model="form.name" type="text" placeholder="请输入姓名"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="联系电话:" :prop="'phone'" :rules="rules.phone">
                 <el-input v-model="form.phone" type="text" placeholder="请输入电话号码"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="
            display: flex;
            justify-content:space-between;
            align-items: center;
            margin-top: 30px;
            margin-left: 100px;
          ">
          <el-button type="primary" :loading="useSaveClick" @click="useSave">确定</el-button>
        </div>

      </div>
    </el-dialog>
    <el-dialog
      title="激活旅游卡"
      :visible.sync="activityVisible"
      width="40%"
      v-el-drag-dialog
      append-to-body
      :before-close="activityClose">
      <div style="position: relative;">
        <el-form ref="activityForm"  :model="activityForm" :rules="rules" label-width="90px">
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="卡号:">
                <span>{{activityForm.sn}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="密码:" :prop="'password'" :rules="rules.password">
                <el-input v-model="activityForm.password" type="password" placeholder="请输入密码" style="width: 300px;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="会员:" :prop="'memberName'" :rules="rules.memberName">
                <el-select v-model="activityForm.memberName" value-key="id" clearable placeholder="请选择会员"
                           filterable @focus="getMemberList" @change="selectMember" :filter-method="queryMember" style="width: 300px;">
                  <el-option v-for="item in memberIdOptions" style="width: 400px;" :key="item.id" :label="item.name" :value="item">
                    <div style="display: flex">
                      <span style="width: 70px;">{{ item.code }}</span>
                      <span style="float: left;width: 150px;overflow: hidden;text-overflow: ellipsis;">{{item.name}}</span>
                      <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{item.mobile}}</span>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toSearchMember">搜索客户</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="
            display: flex;
            justify-content:space-between;
            align-items: center;
            margin-top: 30px;
            margin-left: 100px;
          ">
          <el-button type="primary" :loading="activitySaveClick" @click="activitySave">确定</el-button>
        </div>

      </div>
    </el-dialog>
  </el-container>
  </div>
</template>

<script>
  import ExportList2Excel from "@/components/ExportList2Excel";
  import loadMore from '@/utils/more.js'
  import memberTable from '@/components/MemberTable/index'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {EventBus} from '@/api/eventBus'
  import { list as memberList } from '@/api/member'
  import {update, find, audit, usedCard, validCard, exchangePoint, del} from '@/api/tourist'
  import utils from '../../utils/utils.js'
  import {validatePhone, validateIdNo} from '../../utils/validate'
  import Pagination from '@/components/Pagination'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import { mapGetters } from 'vuex';
  export default {
    name: 'touristCard-view',
    directives: {elDragDialog, permission,loadMore},
    data() {
      const phoneValidate = (rule, value, callback) => {
        if (!value){
          return callback(new Error("请输入联系电话"));
        }else{
          if (!validatePhone(value)) {
            callback(new Error('请输入正确的手机号'))
          } else {
            callback()
          }
        }
      }
      const identityIdValidate = (rule, value, callback) => {
          if (!value){
            return callback(new Error("请输入身份证号"));
          }else{
            if (!validateIdNo(value)) {
              callback(new Error('请输入正确的身份证'))
            } else {
              callback()
            }
          }
      }
      return {
        form: {
          id: '',
          memberId:'',
          receiver: '',
          phone:'',
          name:'',
          identityId:'',
        },
        activityForm:{
          sn:'',
          password:'',
          memberId:'',
          memberName:''
        },
        memberList: [],
        memberIdOptions: [],
        clicked: false,
        isPrintShow:false,
        delClicked:false,
        closeClicked: false,
        transferVisible:false,
        transferSaveClick:false,
        memberTableVisible: false,
        activityClicked: false,
        activityVisible: false,
        activitySaveClick: false,
        useVisible: false,
        useSaveClick: false,
        exchangeSaveClicked: false,
        memberName:'',
        officeName:'',
        sendForm:{},
        operatorName:'',
        times:null,
        auditClicked:false,
        transferClicked:false,
        payLoads:'',
        tabsHeight:null,
        curHeight:null,
        total:0,
        pageNum:1,
        pageSize:20,
        shopName:'',
        rules: {
          identityId: [
            { required: true, validator: identityIdValidate, trigger: 'blur' }
          ],
          phone: [
            { required: true, validator: phoneValidate, trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          receiverName: [
            { required: true, message: '请选择受赠人', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          memberName: [
            { required: true, message: '请选择会员', trigger: 'blur' }
          ]
        }
      }
    },
    watch:{ // 只要路由发生变化就重新获取数据
      $route (newVal, oldVal) {
        if (newVal.name=='touristCard-view' && newVal.query.id!=this.form.id) {
          this.form.id = newVal.query.id;
          this.findClick()
        }
      }
    },
    components:{Distpicker,ExportList2Excel,memberTable,Pagination},
    computed: {
      ...mapGetters([
        'token',
          'scopeType'
      ])
    },
    filters: {
      watchIsExit(val){
        if (val==''){
          return '无'
        }else{
          return  val
        }
      },
      watchStatus(val){
        if (val == 0) {
          return '待领取'
        } else if (val == 1) {
          return '待使用'
        } else if (val == 2) {
          return '已使用'
        } else if (val == 3) {
          return '已完成'
        }else if (val == 9) {
          return '待激活'
        }
      }
    },
    created() {
      var _this = this;
      _this.form.id = this.$route.query.id;
      _this.findClick();
      EventBus.$on('touristCard-view', res => { // 监听新增完毕
        debugger
        _this.form.id = res.id;
        _this.findClick();
      })
    },
    activated() {
      this.payLoads = new Date().getTime()
    },
    mounted(){
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      watchStatus(val){
        if (val == 0) {
          return '待领取'
        } else if (val == 1) {
          return '待使用'
        } else if (val == 2) {
          return '已使用'
        } else if (val == 3) {
          return '已完成'
        }
      },
    queryMember(query) { // 搜索客户
      this.memberIdOptions = []
      memberList({ keyword: query }).then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.memberIdOptions, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getMemberList() { // 加载客户
      memberList().then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.memberIdOptions, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    toSearchMember() {
      this.memberTableVisible = true
    },
    selectMember(data) {debugger
      if (!utils.isNull(data)){
        this.form.receiverName = data.name
        this.form.receiver = data.id;

        this.activityForm.memberId = data.id;
        this.activityForm.memberName = data.name;
      }
    },
    memberDouble(data) {
      this.form.receiverName = data.name
      this.form.receiver = data.id;
      this.memberTableVisible = false
    },
    memberTableClose() {
      this.memberTableVisible = false
    },
      transferClick() {
        this.times=new Date().getSeconds();
        this.transferVisible = true
      },
      transferClose(){
        this.transferVisible = false;
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (_this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight
              _this.curHeight = h - 311//减去页面上固定高度height
              _this.tabsHeight = h - 381
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight
              _this.curHeight = h - 224//减去页面上固定高度height
              this.tabsHeight = h - 294
            }
          })()
        }
      },
      comeIn() {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 224//减去页面上固定高度height
        this.tabsHeight = h - 294
      },
      findClick() {
        var _this = this;//debugger
        find(this.form.id).then(response => {
          _this.form = response.data.touristCard;
          _this.memberName = response.data.touristCard.memberName;
        }).catch(error => {
        })
      },
      loadMember(query) {
        let params = new URLSearchParams();
        params.append("name", query);
        employee(params)
          .then((response) => {
            console.log(response);
            this.memberList = response.data.data;
          })
          .catch((error) => {
            console.log("error!!");
          });
      },
      useClick() {
        this.times=new Date().getSeconds();
        this.useVisible = true;
      },
      useClose(){
        this.useVisible = false;
      },
      auditClick() {
        var _this = this;
        this.$confirm('是否核销?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.auditClicked = true
          audit(this.form.id).then(response => {
            this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
            _this.auditClicked = false
            EventBus.$emit('touristCard-view', response.data)
          }).catch(error => {
            _this.auditClicked = false
          })
        })
      },
      detailsClick(id){
          alert("success" + id);
      },
      transferSave() {
        var _this = this;
/*        if (this.form.receiver == '' || typeof this.form.receiver == 'undefined'){
          this.$message({
              message: '受赠人员为空',
              offset: 120,
              center: true,
              type: 'warning'
            });
          return;
        }*/
        _this.$refs.transferForm.validate((valid)=>{
          if (valid) { // 校验表单
            this.$confirm('是否转赠?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.transferClicked = true;
              delete this.form.memberName;
              delete this.form.receiverName;
              update(this.form).then(response => {
                this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                });
                _this.transferClicked = false
                _this.transferVisible = false;
                EventBus.$emit('touristCard-view', response.data);
              }).catch(error => {
                _this.auditClicked = false
              })
            })
          }

        })
      },
      useSave(){
        var _this = this;
        this.$refs['useForm'].validate((valid) => {
          if (valid) { // 校验表单
            this.$confirm('是否使用?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.useSaveClick = true;
              delete this.form.memberName;
              delete this.form.receiverName;
              usedCard(this.form).then(response => {
                this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                });
                _this.useSaveClick = false;
                _this.useVisible = false;
                EventBus.$emit('touristCard-view', response.data);
              }).catch(error => {
                _this.useSaveClick = false
              })
            })
          }
        });
      },
      activityClose(){
          this.activityVisible = false;
      },
      activityClick(){
        this.times=new Date().getSeconds();
        this.activityForm.sn = this.form.sn;
        this.activityVisible = true
      },
      activitySave(){
        var _this = this;
        this.$refs['activityForm'].validate((valid) => {
          if (valid) { // 校验表单
            this.$confirm('是否激活?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.activitySaveClick = true;
              validCard(this.activityForm).then(response => {
                this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                });
                _this.activitySaveClick = false;
                _this.activityVisible = false;
                EventBus.$emit('touristCard-view', response.data);
              }).catch(error => {
                _this.activitySaveClick = false
              })
            })
          }
        });
      },
      exchangeSaveClick(){
        this.$confirm('是否兑换成购物券?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.exchangeSaveClicked = true;
          exchangePoint(this.form.id).then(response => {
            this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
            this.exchangeSaveClicked = false;
            EventBus.$emit('touristCard-view', response.data);
          }).catch(error => {
            _this.exchangeSaveClicked = false
          })
        })
      }
    }
  }
</script>

<style scoped>
.app{
  height: 80px;
  width: 100%;
  display: flex;
  background-color: rgba(233 ,235,236);
  margin-top: 20px;
}
.deliveryboy{
  height: 100%;
  width: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-right: rgb(245,247,250) 1px solid;
}
.content{
  height: 100%;
  width: 700px;
  display: flex;
  justify-content: space-around;

}
.content_one{
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.summary{
   height: 100%;
   paddding-top:40px;
   paddding-left:40px;
   display: flex;
  flex-direction: column;
  justify-content: space-around;
  margin-left: 20px;
    border-left: rgb(245,247,250) 1px solid;
}
  .box-card {
    width: 100%;
    box-sizing: border-box;
  }

  .details_Header {
    display: flex;
    align-items: center;
  }

  .deleted_Line {
    width: 2px;
    height: 12px;
    background-color: #409EFF;
  }

  .details_HeaderTitle {
    font-weight: 600;
    margin-left: 5px;
    display: block;
    width: 100px;
  }

  .deleted_OrderHeader {
    padding-top: 5px;
    padding-bottom: 10px;
    margin: 10px 0;
    border-left: 1px solid #f2f2f2;
    border-bottom: 1px solid #f2f2f2;
  }

  .deleted_OrderTitle {
  }

  .deleted_OrderContent {
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .details_PayHeader {
    display: flex;
    align-items: center;
    margin-top: 40px;
  }

  .details_Buyers {
    display: flex;
    align-items: center;
  }

  .deleted_Row_Headings {
    color: #666666;
  }

  .deleted_OrderName {
    color: #409EFF;
    margin-left: 5px;
    width: 250px;
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    background-color: #f2f2f2;
    margin-top: 20px;
    font-weight: 600;
  }
  .details_Title {
    font-size: 14px;
    color: #409EFF;
  }
  .details_card {
    overflow: auto;
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
  }
.elOption {
  background-color: #909399;
  color: white;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 40px
}
</style>
